import { invokeAPi } from '@/xz-fn'
import { getHolidayApi } from '@/api/weather'
let timerId0 = null
const fileName = 'holiday.cfg'
const lcoalHoliday = JSON.parse(invokeAPi('config_read', '', fileName) || '{}')
function setHoliday (key, value) {
  lcoalHoliday[key] = value
  invokeAPi('config_write', '', fileName, JSON.stringify(lcoalHoliday))
}
export function initHoliday () {
  getNextHoliday()
  return new Promise((resolve, reject) => {
    getHoliday().then(() => {
      resolve()
    })
  })
}
// 取当前年的数据
export function getHoliday (year, isNext) {
  return new Promise((resolve, reject) => {
    const nowYear = new Date().getFullYear()
    year = year || nowYear
    if (!isNext && (lcoalHoliday[year] || year > nowYear)) { //
      resolve()
      return
    }
    const params = {
      year,
      country: 'cn'
    }
    params.version = lcoalHoliday[year]?.version
    getHolidayApi(params).then(res => {
      if (res.code === 200) {
        const data = res.data || {}
        const list = data.list || []
        let working = []
        let off = []
        list.forEach(item => {
          off = off.concat(item.off || [])
          working = working.concat(item.working || [])
        })
        if (isNext) {
          lcoalHoliday.lastTime = new Date().getTime()
        }
        setHoliday(year, {
          off,
          working,
          year: data.year,
          version: data.version
        })
      } else if (res.code === 404 && year < new Date().getFullYear()) { // 去年以前的数据
        setHoliday(year, {})
      }
    }).finally(() => {
      resolve()
    })
  })
}
// 取下一年的数据
export function getNextHoliday () {
  const nowDate = new Date()
  const nowYear = nowDate.getFullYear()
  const nowMonth = nowDate.getMonth()
  const nowTime = nowDate.getTime()
  const lastTime = lcoalHoliday.lastTime || 0
  if (nowMonth > 9 && nowTime - lastTime > 10 * 24 * 60 * 60 * 1000) {
    const flag = !localStorage.getItem('updated-holiday')
    const time = Math.ceil(Math.random() * (flag ? 0 : 3600) * 1000)
    clearTimeout(timerId0)
    timerId0 = setTimeout(() => {
      getHoliday(nowYear + 1, true)
    }, time)
    localStorage.setItem('updated-holiday', JSON.stringify(true))
  }
}
/**
 * 判断是不是节假日
 * @param {String} date 格式 {y}-{m}-{d}
 * @returns null--正常 false--休  true--班
 */

export function isWork (date) {
  if (!date || typeof date !== 'string') return null
  const arr = date.split('-')
  const year = arr[0]
  const ymd = arr.join('')
  const holiday = lcoalHoliday[year] || {}
  const nextHoli = lcoalHoliday[parseInt(year) + 1] || {}
  if ((holiday.off && holiday.off.includes(ymd)) || (nextHoli.off && nextHoli.off.includes(ymd))) {
    return false
  }
  if (holiday.working && holiday.working.includes(ymd)) {
    return true
  }
  return null
}
